package app.controllers.baseinfo;

import app.Const;
import app.models.iface.Bank;
import com.google.common.base.Strings;
import com.google.common.primitives.Ints;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import goja.mvc.Controller;
import goja.rapid.db.DaoKit;
import org.joda.time.DateTime;

/**
 * <p>
 * The url baseinfo/bank Controller.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
public class BankController extends Controller {

    /**
     * The index route.
     * the url /baseinfo/bank
     * the view in index.ftl
     */
    @Before(GET.class)
    public void index() {}


    /**
     * 列表访问
     */
    @Before(GET.class)
    public void dtlist() {
        renderDataTables(Bank.class);
    }

    @Before(GET.class)
    public void create() {
        Bank bank = new Bank();
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        setAttr(bank);
        render("item.ftl");
    }

    @Before(GET.class)
    public void edit() {
        Bank bank = Bank.dao.findById(getPara());
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        setAttr(bank);
        render("item.ftl");
    }

    @Before(POST.class)
    public void save() {
        Bank bank = getModel(Bank.class);

        final String logo_attachment = getPara("logo");
        if(!Strings.isNullOrEmpty(logo_attachment)){
            bank.set("logo", getPara("logo_url"));
            bank.set("logo_attachment", Ints.tryParse(logo_attachment));
        }

        if (DaoKit.isNew(bank)) {
            bank.set(Const.FIELD_CREATE_TIME, DateTime.now());
            bank.set("enable_flag", Const.YES);
            bank.save();
        } else {
            bank.update();
        }
        redirect("/baseinfo/bank");
    }

    public void delete() {
        int id = getParaToInt(0, 0);
        boolean status = Bank.dao.deleteById(id);
        if (status) {
            renderAjaxSuccess();
        } else {
            renderAjaxFailure();
        }
    }
}